﻿<template>
    <div class="page page-detail">
        <div class="navbar">
            <div class="navbar-bg"></div>
            <div class="navbar-inner navbar-inner-centered-title">
                <div class="left">
                    <a class="link back">
                        <i class="icon icon-back color-primary"></i>
                    </a>
                </div>
                <div class="title text-color-primary">报告</div>
                <div class="right">
                    <a class="link icon-only text-color-primary" id="action-list">
                        <i class="icon f7-icons if-not-md">menu</i>
                        <i class="icon material-icons md-only ">menu</i>
                    </a>
                </div>
            </div>
        </div>
        <div class="page-content">
            <div id="audit-pass-image"></div>
            <form class="list list-strong-ios list-outline-ios list-dividers-ios report-form" id="report-detail-from">
                <ul>
                    <li>
                        <div class="basic-info-container">
                            <div class="container-row">
                                <div class="container-row-left" style="width:70%">
                                    <span class="field-title text-color-primary">检查号：</span><span class="field-text" id="accession-number"></span>
                                </div>
                                <div class="container-row-right" style="width:30%">
                                    <a class="popup-open" href="#" data-popup=".basic-info-popup">
                                        <span class="text-color-primary">详情</span><i class="icon f7-icons if-not-md size-20">chevron_right</i>
                                    </a>
                                </div>
                            </div>
                            <div class="container-row">
                                <div style="width:49%;">
                                    <span class="field-title text-color-primary">姓   名：</span><span class="field-text" id="name"></span>
                                </div>
                                <div style="width:49%">
                                    <span class="field-title text-color-primary">性 别：</span><span class="field-text" id="sex"></span>
                                </div>
                            </div>
                        </div>
                    </li>
                    <!--<li class="item-content" style="margin-bottom:10px;padding-left:0px;">
                        <div class="list accordion-list accordion-container block block-outline" style="padding-right:0px;">
                            <ul>
                                <li class="accordion-item">
                                    <a class="item-link item-content">
                                        <div class="item-inner accordion-title">
                                            <div class="item-title text-color-primary">基本信息</div>
                                        </div>
                                    </a>
                                    <div class="accordion-item-content ">
                                        <div class="report-detail-container">
                                            <div class="container-row">
                                                <div style="width:49%;">
                                                    <span class="field-title text-color-primary">年  龄：</span><span class="field-text" id="age"></span>
                                                </div>
                                                <div style="width:49%">
                                                    <span class="field-title text-color-primary">患者Id：</span><span class="field-text" id="patientId"></span>
                                                </div>
                                            </div>
                                            <div class="container-row">
                                                <div style="width:49%;">
                                                    <span class="field-title text-color-primary"> 门诊号：</span><span class="field-text" id="out-patient-number"></span>
                                                </div>
                                                <div style="width:49%">
                                                    <span class="field-title text-color-primary"> 住院号：</span><span class="field-text" id="in-patient-number"></span>
                                                </div>
                                            </div>
                                            <div class="container-colum">
                                                <span class="field-title text-color-primary">检查部位：</span>
                                                <span style="width:auto;" class="field-text-area" id="exam-body-parties"></span>
                                            </div>
                                            <div class="container-colum">
                                                <span class="field-title text-color-primary">检查方法：</span>
                                                <span style="width:auto;" class="field-text-area" id="exam-methods"></span>
                                            </div>
                                            <div class="container-colum">
                                                <span class="field-title text-color-primary">检查项目：</span>
                                                <span style="width:auto;" class="field-text-area" id="exam-items-detail"></span>
                                            </div>
                                            <div class="container-colum">
                                                <span class="field-title text-color-primary">临床诊断：</span>
                                                <span style="width:auto;" class="field-text-area" id="clinical-diagnosis"></span>
                                            </div>
                                            <br />
                                        </div>
                                    </div>
                                </li>
                            </ul>
                        </div>
                    </li>-->

                    <li class="item-content item-input item-input-outline">
                        <div class="item-inner">
                            <div class="item-title item-label text-color-primary">联系方式</div>
                            <div class="item-input-wrap">
                                <input name="phoneNumber" type="tel" id="phone-number" class="field-require-input" />
                                <span class="input-clear-button"></span>
                            </div>
                        </div>
                    </li>
                    <li class="item-content item-input item-input-outline">
                        <div class="item-inner">
                            <div class="item-title item-label text-color-primary">检查结果</div>
                            <div class="item-input-wrap input-dropdown-wrap">
                                <select name="examResult" value="" id="exam-result" class="field-require-input">
                                    <option value="0">阴性</option>
                                    <option value="1">阳性</option>
                                </select>
                            </div>
                        </div>
                    </li>
                    <li class="item-content item-input item-input-outline " id="li-image-quality">
                        <div class="item-inner">
                            <div class="item-title item-label text-color-primary">图片质量</div>
                            <div class="item-input-wrap input-dropdown-wrap">
                                <select name="reportImageQuality" value="" id="image-quality" class="field-require-input">
                                </select>
                            </div>
                        </div>
                    </li>
                    <li class="item-content item-input item-input-outline mian-textarea" style="position:relative;">
                        <div class="item-inner">
                            <div class="item-title item-label text-color-primary">影像所见</div>
                            <div class="item-input-wrap">
                                <textarea name="imageSeeing" rows="10" class="resizable field-require-input" id="image-seeing"></textarea>
                                <span class="input-clear-button" id="clear-image-seeing"></span>
                            </div>
                        </div>
                    </li>
                    <li class="item-content item-input item-input-outline mian-textarea">
                        <div class="item-inner">
                            <div class="item-title item-label text-color-primary">影像诊断</div>
                            <div class="item-input-wrap">
                                <textarea name="imageDiagnosis" class="resizable field-require-input" id="image-diagnosis"></textarea>
                                <span class="input-clear-button" id="clear-image-diagnosis"></span>
                            </div>
                        </div>
                    </li>
                    <li class="item-content" style="display:none;margin-bottom:10px;padding-left:0px;" id="extend-info">
                        <div class="list  accordion-list accordion-container block block-outline-ios" style="padding-right:0px;">
                            <ul>
                                <li class="accordion-item accordion-item-opened">
                                    <a class="item-link item-content">
                                        <div class="item-inner accordion-title">
                                            <div class="item-title text-color-primary">扩展信息</div>
                                        </div>
                                    </a>
                                    <div class="accordion-item-content">
                                        <ul id="extend-field-container">
                                        </ul>
                                    </div>
                                </li>
                            </ul>
                        </div>
                    </li>
                    <li class="item-content item-input item-input-outline ">
                        <div class="item-inner">
                            <div class="item-title item-label text-color-primary">报告医生</div>
                            <div class="item-input-wrap">
                                <input name="reportDoctor" type="text" id="report-doctor" class="disabled" />
                                <span class="input-clear-button"></span>
                            </div>
                        </div>
                    </li>
                    <li class="item-content item-input item-input-outline ">
                        <div class="item-inner">
                            <div class="item-title item-label text-color-primary">报告日期</div>
                            <div class="item-input-wrap">
                                <input name="reportTime" type="text" id="report-time" class="disabled" />
                                <span class="input-clear-button"></span>
                            </div>
                        </div>
                    </li>
                    <li class="item-content item-input item-input-outline">
                        <div class="item-inner ">
                            <div class="item-title item-label text-color-primary">审核医生</div>
                            <div class="item-input-wrap">
                                <input name="auditDoctor" type="text" id="audit-doctor" class="disabled" />
                                <span class="input-clear-button"></span>
                            </div>
                        </div>
                    </li>
                    <li class="item-content item-input item-input-outline ">
                        <div class="item-inner">
                            <div class="item-title item-label text-color-primary">审核日期</div>
                            <div class="item-input-wrap">
                                <input name="auditTime" type="text" id="audit-time" class="disabled" />
                                <span class="input-clear-button"></span>
                            </div>
                        </div>
                    </li>
                    <li class="item-content item-input item-input-outline ">
                        <div class="item-inner">
                            <div class="item-title item-label text-color-primary">复审医生</div>
                            <div class="item-input-wrap">
                                <input name="inPatientNumber" type="text" class="disabled" />
                                <span class="input-clear-button"></span>
                            </div>
                        </div>
                    </li>
                    <li class="item-content item-input item-input-outline ">
                        <div class="item-inner">
                            <div class="item-title item-label text-color-primary">复审日期</div>
                            <div class="item-input-wrap">
                                <input name="inPatientNumber" type="text" class="disabled" />
                                <span class="input-clear-button"></span>
                            </div>
                        </div>
                    </li>
                </ul>
            </form>
        </div>
        <div style="display:none" id="iframe-hidden-container" examId="">
            <iframe src="../mobile/index" sandbox="allow-forms allow-scripts allow-top-navigation allow-same-origin">
            </iframe>
        </div>
        <div class="popup revoke-popup">
            <div class="view view-init safe-areas" id="revoke-view" data-url="/revoke/">
            </div>
        </div>
        <div class="popup image-popup popup-tablet-fullscreen">
            <div class="view view-init safe-areas" id="image-view" data-url="/chart/">
            </div>
        </div>
        <div class="popup reject-popup">
            <div class="view view-init safe-areas" id="reject-view" data-url="/reject/">
            </div>
        </div>
        <div class="popup amend-popup">
            <div class="view view-init safe-areas" id="amend-view" data-url="/amend/">
            </div>
        </div>
        <div class="popup followup-record-popup">
            <div class="view view-init safe-areas" id="followup-record-view" data-url="/followup-record/">
            </div>
        </div>
        <div class="popup verify-user-popup">
            <div class="view view-init safe-areas" id="amend-view" data-url="/verify-user/">
            </div>
        </div>
        <div class="popup template-popup">
            <div class="view view-init safe-areas" id="template-view" data-url="/template/">
            </div>
        </div>
        <div class="popup basic-info-popup">
            <div class="view view-init safe-areas" id="basic-info-view" data-url="/basic-info/">
            </div>
        </div>
    </div>
</template>
<script>
    export default (props, { $, $on, $f7, $h, $f7router, $f7route, $theme, $onMounted, $onBeforeUnmount, $update, $store }) => {
        /*
            $   Dom7 标准库
            $on 页面事件处理器绑定
            $f7 app实例对象
            $h  html模板字面量
        */
        let actionSheet, examId, reportId, actionType, permissions, totalPermissions, editable = false, exam, patient, report, toast;
        let imageOpenCount = 0;
        $on('pageInit', (e, page) => {
            $f7.preloader.show();
            getParamsFromQuery(page.route.query);
            loadReport()
                .then(() => {
                    $f7.preloader.hide();
                    actionSheetInit(permissions);
                })
                .then(() => {
                    $("#action-list").on("click", () => { // 监听打开按钮列表
                        actionSheet.open();
                    });
                    isEditable(editable);
                })
            loadImageQuality();
            addRevokeSucceedListenner();
            addAmendAllowedListener();
            $(".toolbar").hide();
            $f7.on('templateApply', (actionType, template) => {
                applyTemplate(actionType, template);
            })
        });

        // 接收query
        const getParamsFromQuery = (query) => {
            examId = query.examId;
            reportId = query.reportId;
            $store.state.reportId = reportId;
            $store.state.examId = examId;
            actionType = query.actionId;
            totalPermissions = query.permissions;
        }

        // 加载报告
        const loadReport = (isSilent) => {
            return new Promise((resolve) => {
                fetch(`/api/report/get-exam/${reportId}`, {
                    method: 'GET',
                    headers: { 'Content-Type': 'application/json' }
                }).then((res) => {
                    res.json().then((result) => {
                        exam = result.data;
                        patient = exam.patient;
                        report = exam.report;
                        report.reportExtending = JSON.parse(report.reportExtending);
                        $store.state.report = report;
                        $store.state.exam = exam; // 更新状态中检查数据
                        permissions = report.permissions;
                        editable = report.isEditing;
                        if (!isSilent) {
                            $("#accession-number").html(exam.accessionNumber);
                            $("#name").html(patient.name);
                            $("#sex").html(patient.sex === 0 ? '男' : (patient.sex === 1 ? '女' : '其他'));
                            $("#age").html(exam.age);
                            $("#patientId").html(patient.patientId);
                            $("#out-patient-number").html(exam.outPatientNumber);
                            $("#in-patient-number").html(exam.inPatientNumber);
                            $("#phone-number").val(patient.phoneNumber);
                            $("#exam-items-detail").html(exam.examItemsText);
                            $("#exam-body-parties").html(exam.examBodyPartiesText);
                            $("#exam-methods").html(exam.examMethodsText);
                            $("#clinical-diagnosis").val(exam.clinicalDiagnosis);
                            $("#clinical-diagnosis").css('height', `${$("#clinical-diagnosis").prop('scrollHeight')}px`);  // 设置外框高度
                            $("#exam-result").val(report.examResult);
                            $("#image-quality").val(report.reportImageQuality);
                            setHeight(report); // 设置文本域高度
                        }
                        if ([8].indexOf(report.reportStatus) !== -1) {
                            $("#audit-pass-image").append('<img class="report-audited" src = "/images/report-audited.png" style="height:100%;width:100%"/>');
                            $("#audit-pass-image").show();
                        }
                        $("#report-doctor").val(report.reportDoctor);
                        $("#audit-doctor").val(report.auditDoctor);
                        $("#report-time").val(report.reportTime);
                        $("#audit-time").val(report.auditTime);
                        fetch(`/api/report/get-extend-fields/${reportId}`, { method: 'GET', headers: { 'Content-Type': 'application/json' } })
                            .then((res2) => {
                                res2.json().then((fields) => {
                                    report.extendFields = fields;
                                    if (report.extendFields && report.extendFields.length && report.extendFields.length > 0) {
                                        extendInfo();
                                    }
                                    resolve();
                                });
                            })
                    });
                })

            })
        }

        // 文本域高度
        const setHeight = (report) => {
            // 图像可见高度
            let $imageSee = $("#image-seeing");
            $imageSee.val(report.imageSeeing);
            let seeHeightStr = $imageSee.css('height');
            let seeScrollHeght = $imageSee.prop('scrollHeight');
            seeHeightStr = seeHeightStr.slice(0, seeHeightStr.length - 2);
            if (parseInt(seeHeightStr, 10) < seeScrollHeght) {
                $imageSee.css('height', seeScrollHeght + 'px');
            }

            // 图像诊断高度
            let $diagnosis = $("#image-diagnosis");
            $diagnosis.val(report.imageDiagnosis);
            $diagnosis.css('height', '100px');
            let actualHeight = $diagnosis.css('height');
            let scrollHeight = $diagnosis.prop('scrollHeight');
            actualHeight = actualHeight.slice(0, actualHeight.length - 2);
            if (parseInt(actualHeight, 10) < scrollHeight) {
                $diagnosis.css('height', scrollHeight + 'px');
            }
        }

        // 加载图片质量选项
        const loadImageQuality = () => {
            fetch(`/api/report/image-quality-options?reportId=${reportId}`, {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' }
            }).then((res) => {
                res.json().then((result) => {
                    if (result.length > 0) {
                        let str = '';
                        result.map((item) => {
                            str += `<option value="${item.value}">${item.label}</option>`;
                        });
                        $("#image-quality").append(str);
                    }
                    else {
                        $("#li-image-quality").hide();
                    }
                });
            })
        }

        // 图像弹窗打开完成事件
        const listenToImageByInterval = () => {
            $('.image-popup').show();
            $('.popup-backdrop').show();
            imageOpenCount++;
            let interval = setInterval(() => {
                if ($(".view-image-page #image-page-content").length > 0) {
                    let $hiddenContainer = $(".page-detail #iframe-hidden-container");
                    let hiddenIframe = $(".page-detail #iframe-hidden-container").html();
                    let $pageContent = $(".view-image-page #image-page-content");
                    let id = $hiddenContainer.attr("examId");
                    if (id !== examId) {
                        $hiddenContainer.attr("examId", examId);
                        $pageContent.html(''); // 清空
                        fetch(`/api/exam/get-dicom-client-url`, {
                            method: 'GET',
                            headers: { 'Content-Type': 'application/json' }
                        }).then((res) => {
                            res.json().then((result) => {
                                if (result.success && result.data) {
                                    let url = result.data;
                                    if (result.data.includes('?')) {
                                        url += `&examIds=${examId}`;
                                    } else {
                                        url += `?examIds=${examId}`;
                                    }
                                    $pageContent.append(hiddenIframe);
                                    $pageContent.find('iframe').attr('src', url);
                                    $(".page-detail #iframe-hidden-container").find('iframe')[0].contentWindow.location = url;
                                    imageOpenCount++;
                                }
                            });
                        })
                    }
                    clearInterval(interval);
                }
            }, 500);
        }

        // 初始化action-sheet
        const actionSheetInit = (permissions) => {
            return new Promise((resolve) => {
                let buttons = [];
                let buttonGroup1 = [];
                let buttonGroup2 = [];
                buttonGroup1.push({
                    text: "查看图像",
                    color: "primary",
                    onClick: function (actions, e) {
                        if (imageOpenCount === 0) {
                            $f7.popup.open(".image-popup", true);
                        }
                        listenToImageByInterval();
                    }
                })
                if (permissions.indexOf("报告_保存") !== -1 && totalPermissions.indexOf("报告_保存") !== -1) {
                    buttonGroup1.push({
                        text: "保存报告",
                        color: "primary",
                        onClick: function (actions, e) {
                            $f7.preloader.show();
                            saveReport(false).then(() => { $f7.preloader.hide(); });
                        }
                    })
                }
                if (permissions.indexOf("报告_提交报告") !== -1 && totalPermissions.indexOf("报告_提交报告") !== -1) {
                    buttonGroup1.push({
                        text: "提交报告",
                        color: "primary",
                        onClick: function (actions, e) {
                            submit(false);
                        }
                    })
                }
                if (permissions.indexOf("报告_放弃书写") !== -1 && totalPermissions.indexOf("报告_放弃书写") !== -1) {
                    buttonGroup1.push({
                        text: "放弃书写",
                        color: "primary",
                        onClick: function (action, e) {
                            reportGiveUp();
                        }
                    })
                }
                if (permissions.indexOf("报告_审核报告") !== -1 && totalPermissions.indexOf("报告_审核报告") !== -1) {
                    buttonGroup1.push({
                        text: "审核报告",
                        color: "primary",
                        onClick: function (action, e) {
                            startAudit();
                        }
                    });
                }
                if (permissions.indexOf("报告_通过审核") !== -1 && totalPermissions.indexOf("报告_通过审核") !== -1) {
                    buttonGroup1.push({
                        text: "通过审核",
                        color: "primary",
                        onClick: function (action, e) {
                            submit(true); //  complete 参数为true ，直接提交完成；
                        }
                    })
                }
                if (permissions.indexOf("报告_撤回") !== -1 && totalPermissions.indexOf("报告_撤回") !== -1) {
                    let text;
                    switch (report.reportStatus) {
                        case 1:
                            text = "撤回报告";
                            break;
                        case 3:
                            //已提交报告  撤回提交
                            text = "撤回报告";
                            break;
                        case 5:
                            //已审核  撤回审核 / 申请复审（提交并且复审）
                            text = "撤回审核";
                            break;
                        case 8:
                            //已完成  撤回 / 复审报告（权限允许自审）
                            text = "撤回审核";
                            break;
                    }
                    buttonGroup1.push({
                        text: text,
                        color: "primary",
                        onClick: function (action, e) {
                            $store.state.revokeTitle = text;
                            $f7.popup.open('.revoke-popup');
                        }
                    })
                }
                if (permissions.indexOf("报告_驳回重写") !== -1 && totalPermissions.indexOf("报告_驳回重写") !== -1 && (report.reportStatus === 4 || report.reportStatus === 6)) {
                    buttonGroup1.push({
                        text: "驳回重写",
                        color: "primary",
                        onClick: function (action, e) {
                            $f7.popup.open(".reject-popup");
                        }
                    })
                }
                if (editable) {
                    buttonGroup1.push({
                        text: "诊断模板",
                        color: "primary",
                        onClick: function (action, e) {
                            $f7.popup.open(".template-popup");
                        }
                    });
                }
                if (permissions.indexOf("报告_修正报告") !== -1 && totalPermissions.indexOf("报告_修正报告") !== -1) {
                    buttonGroup1.push({
                        text: "修正",
                        color: "primary",
                        onClick: function (action, e) {
                            $f7.popup.open(".amend-popup");
                        }
                    })
                }
                if (permissions.indexOf("报告_申请复审") !== -1 && totalPermissions.indexOf("报告_申请复审") !== -1) {
                    buttonGroup1.push({
                        text: "申请复审",
                        color: "primary",
                        onClick: function (action, e) {
                            submit(false);
                        }
                    })
                }
                if (!report.isFollowup && totalPermissions.indexOf("报告_标记随访") !== -1) {
                    buttonGroup1.push({
                        text: "标记随访",
                        color: "primary",
                        onClick: function (action, e) {
                            markFollowUp();
                        }
                    })
                }
                if (report.isFollowup) {
                    buttonGroup1.push({
                        text: "放弃随访",
                        color: "primary",
                        onClick: function (action, e) {
                            markFollowUp();
                        }
                    });
                }
                if (buttonGroup1.length > 0) {
                    buttonGroup1.unshift({
                        text: "操作",
                        label: true
                    });
                    buttonGroup2.push({
                        text: "取消",
                        color: "red",
                        onClick: () => {
                            actionSheet.close();
                        }
                    })
                }
                if (buttonGroup1.length > 0 && buttonGroup2.length > 0) {
                    buttons.push(buttonGroup1);
                    buttons.push(buttonGroup2);
                    actionSheet = $f7.actions.create({
                        buttons: buttons,
                        closeByOutsideClick: true,
                        backdrop: true
                    });
                }
                resolve();
            })
        }

        // 是否可編輯
        const isEditable = (isEditing) => {
            if (!isEditing) {
                //$("#phone-number").addClass("disabled");
                //$("#exam-result").addClass("disabled");
                //$("#image-quality").addClass("disabled");
                //$("#image-seeing").addClass("disabled");
                //$("#image-diagnosis").addClass("disabled");
                $(".field-require-input").removeClass("disabled");
                $(".field-require-input").addClass("disabled");
                $("#template-fab").hide();
            }
            else {
                $("#template-fab").show();
                $(".field-require-input").removeClass("disabled");
            }
        }

        const showToast = (text) => {
            return new Promise((resolve) => {
                toast = $f7.toast.create({
                    text: text,
                    position: 'center',
                    closeTimeout: 2000,
                });
                toast.open();
                resolve();
            })

        }

        // 保存
        const saveReport = (isSubmit) => {
            return new Promise((resolve) => {
                if (report) {
                    let formData = $f7.form.convertToData("#report-detail-from")
                    if (!formData.examResult && isSubmit) {
                        showToast('请选择"检查结果"！');
                        return;
                    }
                    if (!formData.reportImageQuality && isSubmit) { // 提交保存
                        showToast('请选择"图像质量"！');
                        return;
                    }
                    if (!formData.imageSeeing && isSubmit) {
                        showToast('请填写"图像所见"');
                        return;
                    }
                    if (!formData.imageDiagnosis && isSubmit) {
                        showToast('请填写"图像诊断"！');
                        return;
                    }
                    report.examResult = formData.examResult ? formData.examResult : null;
                    report.id = report.oid;
                    report.imageDiagnosis = formData.imageDiagnosis ? formData.imageDiagnosis : '';
                    report.imageSeeing = formData.imageSeeing ? formData.imageSeeing : '';
                    report.reportImageQuality = formData.reportImageQuality ? formData.reportImageQuality : '';
                    report.phoneNumber = formData.phoneNumber ? formData.phoneNumber : '';
                    // 扩展字段
                    let extending = {};
                    $("#extend-field-container .field-require-input").map((item) => {
                        let key = $(item).attr('fieldName');
                        extending[key] = $(item).val();
                    })
                    report.reportExtending = JSON.stringify(extending);
                    fetch(`/api/report/save-mobile`, {
                        method: 'POST',
                        body: JSON.stringify(report),
                        headers: { 'Content-Type': 'application/json' }
                    }).then((res) => {
                        res.json().then((result) => {
                            if (!isSubmit) {
                                if (result.success) {
                                    $f7.dialog.alert(`<span class="text-color-primary"><b>保存成功！</b></span>`, '提示')
                                    resolve();
                                }
                                else {
                                    $f7.dialog.alert(`<span class="text-color-primary"><b>${result.error}</b></span>`, '错误');
                                    resolve();
                                }
                            }
                            else {
                                if (result.success) {
                                    resolve(true);
                                }
                                else {
                                    $f7.dialog.alert(`<span class="text-color-red"><b>${result.error}</b></span>`, '');
                                    resolve(false);
                                }
                            }
                        });
                    })
                }
            })
        }

        // 提交前验证
        const validate = () => {
            return new Promise((resolve) => {
                let type = 'Report';
                fetch(`/api/exam/validate-mobile`, {
                    method: 'POST',
                    body: JSON.stringify({ examId, type }),
                    headers: { 'Content-Type': 'application/json' }
                }).then((res) => {
                    res.json().then((result) => {
                        if (result.success && result.data) {
                            let hasWarn = false;
                            let hasError = false;
                            const $message = $('<div class="exam-validation-result" />');
                            for (const level in result.data) {
                                for (const message of result.data[level]) {
                                    switch (level) {
                                        case 'Info':
                                            $message.append(
                                                $('<div class="info result-item" />')
                                                    .append($(`<i class="icon fa fa-info-circle" />`))
                                                    .append($(`<span class="message">${message}</span>`)
                                                    )
                                            );
                                            break;
                                        case 'Warn':
                                            hasWarn = true;
                                            $message.append(
                                                $('<div class="warn result-item" />')
                                                    .append($(`<i class="icon fa fa-warning" />`))
                                                    .append($(`<span class="message">${message}</span>`)
                                                    )
                                            );
                                            break;
                                        case 'Error':
                                            hasError = true;
                                            $message.append(
                                                $('<div class="error result-item" />')
                                                    .append($(`<i class="icon fa fa-times-circle" />`))
                                                    .append($(`<span class="message">${message}</span>`)
                                                    )
                                            );
                                            break;
                                    }
                                }
                            }
                            if ($message.children.length > 0) {
                                if (hasError) {
                                    $message.addClass('text-color-red');
                                    $f7.dialog.alert($message.prop('outerHTML'), '错误')
                                        .then(() => {
                                            resolve(false);
                                        });
                                }
                                else {
                                    $f7.dialog.alert($message.prop('outerHTML'), '提示').then(resolve(false));
                                }
                            }
                        }
                        else {
                            resolve(true);
                        }
                    });
                })
            });
        }

        // 提交
        const submit = (complete) => {
            saveReport(true)
                .then((res) => {
                    $f7.preloader.show();
                    if (res) {
                        return validate();
                    }
                    else {
                        return;
                    }
                })
                .then((result) => {
                    if (result) {
                        fetch(`/api/report/submit-mobile`, {
                            method: 'POST',
                            body: JSON.stringify({ reportId: report.oid, complete: complete }),
                            headers: { 'Content-Type': 'application/json' }
                        }).then((res) => {
                            res.json().then((result) => {
                                if (result.success) {
                                    if (complete) { // 审核修正提交
                                        submitCallBack()
                                            .then(() => {
                                                $f7.dialog.alert(`<span class="text-color-primary"><b>审核完成！</b></span>`, '提示');
                                            });
                                    }
                                    else {
                                        if (report.reportStatus == 2 && totalPermissions.indexOf("报告_审核自审") !== -1) {
                                            startAudit();
                                        }
                                        else {
                                            submitCallBack()
                                                .then(() => {
                                                    $f7.dialog.alert(`<span class="text-color-primary"><b>提交成功！</b></span>`, '提示');
                                                });
                                        }
                                    }
                                }
                                else {
                                    $f7.preloader.hide();
                                    $f7.dialog.alert(`<span class="text-color-red"><b>${result.error}</b></span>`, '错误');
                                }
                            });
                        })
                    }
                    else {
                        return;
                    }
                })
        }

        // 提交回调
        const submitCallBack = () => {
            return new Promise((resolve) => {
                loadReport(true)
                    .then(() => {
                        if (actionSheet) {
                            actionSheet.destroy();
                        }
                        actionSheetInit(permissions)
                            .then(() => {
                                $f7.preloader.hide();
                            });
                    })
                    .then(() => {
                        isEditable(false);
                        resolve();
                    })
            })

        }

        // 撤回成功监听
        const addRevokeSucceedListenner = () => {
            $f7.on('revokeSuccess', () => {
                refreshPage();
            })
        }

        // 放弃书写
        const reportGiveUp = () => {
            $f7.dialog.confirm('当前已书写的内容不会保存，确定放弃书写吗?', '放弃书写', () => {
                $f7.preloader.show();
                fetch(`/api/report/give-up-write-report-mobile/`, {
                    method: 'POST',
                    body: JSON.stringify(reportId),
                    headers: { 'Content-Type': 'application/json' }
                }).then((res) => {
                    res.json().then((result) => {
                        if (result.success) {
                            $f7.preloader.hide();
                            $store.state.report = { reportStatus: -1 };// -1未报告
                            $f7router.back();
                        }
                        else {
                            $f7.dialog.alert(`<span class="text-color-red"><b>${result.error}</b></span>`, '错误');
                        }
                    });
                })
            },
                () => {
                    return;
                })
        }

        // 监听修正
        const addAmendAllowedListener = () => {
            $f7.on('amendAllowed', () => {
                refreshPage();
            })
        }

        // 开始审核
        const startAudit = () => {
            fetch(`/api/report/audit/${examId}`, {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' }
            }).then((res) => {
                res.json().then((result) => {
                    if (result.success) {
                        submitCallBack()
                            .then(() => {
                                $f7.dialog.alert(`<span class="text-color-primary"><b>提交成功！</b></span>`, '提示');
                            });
                    }
                    else {
                        $f7.preloader.hide();
                        $f7.dialog.alert(`<span class="text-color-red"><b>${result.error}</b></span>`, '错误');
                    }
                });
            })
        }

        // 标记随访
        const markFollowUp = () => {
            $f7.preloader.show();
            fetch(`/api/report/mark-follow-up/${reportId}`, {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' }
            }).then((res) => {
                res.json().then((result) => {
                    if (result.success && report.isFollowup) {
                        $f7.preloader.hide();
                        $f7.dialog.alert(`<span class="text-color-primary"><b>随访已放弃!</b></span>`, '提示', loadActionSheet(false))
                    }
                    else if (result.success && !report.isFollowup) {
                        $f7.preloader.hide();
                        $f7.dialog.alert(`<span class="text-color-primary"><b>已标记随访!</b></span>`, '提示', loadActionSheet(true));
                    }
                    else if (!result.success) {
                        $f7.preloader.hide();
                        $f7.dialog.alert(`<span class="text-color-red"><b>${result.error}</b></span>`, '错误');
                    }
                });
            })
        }

        // 重新加载actionSheet
        const loadActionSheet = (isFollowup) => {
            actionSheet.destroy();
            if (isFollowup) {
                report.isFollowup = true;
            }
            else {
                report.isFollowup = false;
            }
            actionSheetInit(permissions);
        }

        // 应用模板内容
        const applyTemplate = (actionType, template) => {
            report.imageSeeing = $("#image-seeing").val();
            report.imageDiagnosis = $("#image-diagnosis").val();
            if (actionType === 'replace') {
                report.imageSeeing = template.imageSeeing;
                report.imageDiagnosis = template.imageDiagnosis;
                setHeight(report);
            }
            else if (actionType === 'append') {
                report.imageSeeing += ('\n' + template.imageSeeing);
                report.imageDiagnosis += ('\n' + template.imageDiagnosis);
                setHeight(report);
            }
        }

        // 扩展信息
        const extendInfo = () => {
            let exntends = report.extendFields;
            let $liOuter = $("#extend-info");
            let $lu = $liOuter.find(".accordion-container  #extend-field-container");
            let str = '';
            if (exntends.length > 0) {
                exntends.map((item) => {
                    if (!item.type) {
                        str += `<li class="item-content item-input item-input-outline item-in-accordion-ul ">
                                    <div class="item-inner">
                                        <div class="item-title item-label text-color-primary">${item.fieldName}</div>
                                        <div class="item-input-wrap">
                                            <input name="${item.fieldName}" type="text" fieldName="${item.fieldName}" class="field-require-input" />
                                        </div>
                                    </div>
                               </li>`;
                    }
                    else {
                        switch (item.type) {
                            case "Integer":
                                str += `<li class="item-content item-input item-input-outline item-in-accordion-ul ">
                                            <div class="item-inner">
                                                <div class="item-title item-label text-color-primary">${item.fieldName}</div>
                                                <div class="item-input-wrap">
                                                    <input name="${item.fieldName}" type="number" fieldName="${item.fieldName}" class="field-require-input" />
                                                </div>
                                            </div>
                                        </li>`;
                                break;
                            case "Float":
                                str += `<li class="item-content item-input item-input-outline item-in-accordion-ul ">
                                            <div class="item-inner">
                                                <div class="item-title item-label text-color-primary">${item.fieldName}</div>
                                                <div class="item-input-wrap">
                                                    <input name="${item.fieldName}" type="number" fieldName="${item.fieldName}" class="field-require-input" />
                                                </div>
                                            </div>
                                        </li>`;
                                break;
                            case "String":
                                str += `<li class="item-content item-input item-input-outline item-in-accordion-ul ">
                                            <div class="item-inner">
                                                <div class="item-title item-label text-color-primary">${item.fieldName}</div>
                                                <div class="item-input-wrap">
                                                    <input name="${item.fieldName}" type="text" fieldName="${item.fieldName}" class="field-require-input" />
                                                </div>
                                            </div>
                                        </li>`;
                                break;
                            case "Boolean":
                                str += `<li class="item-content item-input item-input-outline  item-in-accordion-ul" style="justify-content:flex-start">
                                               <div class="item-inner">
                                                 <div class="item-title item-label text-color-primary">${item.fieldName} ：</div>
                                                 <div class="item-input-wrap input-dropdown-wrap">
                                                                        <select name="${item.fieldName}"  fieldName="${item.fieldName}"  class="field-require-input" >
                                                                            <option value="true" selected >是</option>
                                                                            <option value="false">否</option>
                                                                        </select>
                                                 </div>
                                               </div>
                                         </li>`;
                                break;
                            case "Date":
                                str += `<li class="item-content item-input item-input-outline item-in-accordion-ul ">
                                          <div class="item-inner">
                                              <div class="item-title item-label text-color-primary">${item.fieldName}</div>
                                              <div class="item-input-wrap">
                                                  <input name="${item.fieldName}" type="date" fieldName="${item.fieldName}" class="field-require-input" />
                                              </div>
                                          </div>
                                      </li>`;
                                break;
                            case "Time":
                                str += `<li class="item-content item-input item-input-outline item-in-accordion-ul ">
                                          <div class="item-inner">
                                              <div class="item-title item-label text-color-primary">${item.fieldName}</div>
                                              <div class="item-input-wrap">
                                                  <input name="${item.fieldName}" type="datetime-local" fieldName="${item.fieldName}" class="field-require-input" />
                                              </div>
                                          </div>
                                      </li>`;
                                break;
                            case "Enum":
                                let options = '';
                                let extendValue;
                                if (report.reportExtending && report.reportExtending[item.fieldName]) {
                                    extendValue = report.reportExtending[item.fieldName];
                                }
                                if (item.valueRange) {
                                    let values = item.valueRange.split(',');
                                    values.map((value) => {
                                        let selected = '';
                                        if (extendValue && extendValue.indexOf(value) >= 0) {
                                            selected = 'selected';
                                        }
                                        options += `<option value="${value}" ${selected} >${value}</option>`
                                    })
                                }
                                str += `<li class=" item-in-accordion-ul">
                                            <a class="item-link smart-select smart-select-init"  id="${item.fieldName}" data-open-in="popover" style="margin-left:0px !important">
                                                <select name="${item.fieldName}"  fieldName="${item.fieldName}"  class="field-require-input" ${item.isMultiValue ? 'multiple' : ''}>
                                                    ${options}
                                                </select>
                                                <div class="item-content">
                                                  <div class="item-inner">
                                                    <div class="item-title text-color-primary">${item.fieldName} ：</div>
                                                  </div>
                                                </div>
                                            </a>
                                        </li>`;
                                break;
                            default:
                                break;
                        }
                    }
                })
                $lu.append(str);
                $liOuter.show();
                if (report.reportExtending) {
                    exntends.map((item) => {
                        if (report.reportExtending[item.fieldName]) {
                            if (item.type !== "Enum") {
                                let value = report.reportExtending[item.fieldName];
                                $lu.find(`[name=${item.fieldName}]`).val(value);
                            }
                        }
                    })
                }
            }
        }
        // 页面刷新
        const refreshPage = () => {
            $f7router.refreshPage();
        }
        return $render;
    };
</script>
